<template>
  <div class="list-table">
    <div class="nospecialModel ">
      <div class="area-header">
        <span class="area-header-title">{{ $t('撰写报告') }}</span>
      </div>
    </div>

    <el-table v-loading="loading" tooltip-effect="darkTable" :data="listData" border>
      <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="150">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('文件名称')" align="center" prop="fileName" show-overflow-tooltip min-width="380" />
      <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" min-width="300">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="text"
            icon="el-icon-download"
            @click="createFile(scope.row)"
          >{{ $t('生成报告') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog v-loading="loadingFile" v-el-drag-dialog :title="$t('生成报告')" :visible.sync="fileOpen" width="40%" class="dataForm" :close-on-click-modal="false" :lock-scroll="false">
      <div style="height: 450px;overflow: auto;padding: 20px;margin: -20px;">
        <el-form ref="form" :model="queryParams" label-width="80px">
          <el-row>
            <el-col :span="24">
              <el-form-item :label="$t('截止日期')" prop="endDate">
                <el-date-picker
                  v-model="queryParams.endDate"
                  type="month"
                  placeholder="截止日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('基金名称')" prop="investorIds">
                <el-select v-model="arrayParams.investorIds" filterable multiple :placeholder="$t('基金名称')" clearable @change="changeData()">
                  <el-option
                    v-for="fund in fundOptions"
                    :key="fund.id"
                    :label="$t(fund.fundName)"
                    :value="fund.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('项目行业')" prop="dealIndustrys">
                <el-select v-model="arrayParams.dealIndustrys" filterable multiple :placeholder="$t('项目行业')" clearable @change="changeData()">
                  <el-option
                    v-for="dict in dealIndustryOptions"
                    :key="dict.dictValue"
                    :label="$t(dict.dictLabel)"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('项目名称')" prop="dealIds">
                <el-select v-model="arrayParams.dealIds" filterable multiple :placeholder="$t('项目名称')" clearable>
                  <el-option
                    v-for="deal in dealOptions"
                    :key="deal.id"
                    :label="$t(deal.dealName)"
                    :value="deal.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="createQuarterlyReport">{{ $t("生成报告") }}</el-button>
        <el-button @click="formCancel">{{ $t("取消") }}</el-button>
      </div>
    </el-dialog>
    <!--  后两个报告生成  -->
    <el-dialog v-loading="loadingFileTwo" v-el-drag-dialog :title="$t('生成报告')" :visible.sync="fileOpenTwo" width="40%" class="dataForm" :close-on-click-modal="false" :lock-scroll="false">
      <div style="height: 450px;overflow: auto;padding: 20px;margin: -20px;">
        <el-form ref="form" :model="queryParams" label-width="80px">
          <el-row>
            <el-col :span="24">
              <el-form-item :label="$t('基金名称')">
                <el-select v-model="queryParams.fundId" filterable :placeholder="$t('基金名称')" clearable @change="getLpBaseByFundId">
                  <el-option
                    v-for="fund in fundOptions"
                    :key="fund.id"
                    :label="$t(fund.fundName)"
                    :value="fund.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="queryParams.reportType === 'lpEquityReport'" :span="24">
              <el-form-item :label="$t('出资人')">
                <el-select v-model="queryParams.lpIds" filterable :placeholder="$t('请选择出资人')">
                  <el-option
                    v-for="item in lpOptions"
                    :key="item.lpId"
                    :label="item.shortName"
                    :value="item.lpId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('年份')">
                <el-select v-model="queryParams.year" placeholder="年份" filterable clearable>
                  <el-option
                    v-for="item in filterOptionArr"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('季度')">
                <el-select v-model="queryParams.quarter" filterable :placeholder="$t('季度')" clearable>
                  <el-option
                    v-for="quarter in quarterArr"
                    :key="quarter.value"
                    :label="$t(quarter.label)"
                    :value="quarter.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <template v-if="queryParams.reportType === 'lpEquityReport'" :span="24">
              <el-col :span="24">
                <el-form-item :label="$t('结束年份')">
                  <el-select v-model="queryParams.endYear" placeholder="结束年份" filterable clearable>
                    <el-option
                      v-for="item in filterOptionArr"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label="$t('结束季度')">
                  <el-select v-model="queryParams.endQuarter" filterable :placeholder="$t('结束季度')" clearable>
                    <el-option
                      v-for="quarter in quarterArr"
                      :key="quarter.value"
                      :label="$t(quarter.label)"
                      :value="quarter.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label="$t('计算方式')">
                  <dict-select
                    v-model="queryParams.calculation"
                    dictionary="report_calculation"
                  />
                </el-form-item>
              </el-col>
            </template>
          </el-row>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="createQuarterlyReport">{{ $t("生成报告") }}</el-button>
        <el-button @click="formCancel">{{ $t("取消") }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listDeal, findFundList } from '@/api/sass/kaihui/dashboard/kaiHuiDashboard'
import { getToken } from '@/utils/auth'
import axios from 'axios'
import { findLpBaseList } from '@/api/fund/lpBase/lpBase'

export default {
  data() {
    return {
      // 遮罩层
      loading: false,
      // 生成报告加载窗
      loadingFile: false,
      loadingFileTwo: false,
      // 生成报告弹出窗
      fileOpen: false,
      fileOpenTwo: false,
      // 表格数据
      listData: [
        {
          num: 1,
          fileName: 'Quarterly Review-by deal',
          reportType: 'quarterlyReviewbydeal'
        },
        {
          num: 2,
          fileName: 'Fund - Value Creation_China Portfolio',
          reportType: 'fundValueCreationChinaPortolio'
        },
        {
          num: 3,
          fileName: '基金信披报告',
          reportType: 'fundDisclosureReport'
        },
        {
          num: 2,
          fileName: 'LP权益报告',
          reportType: 'lpEquityReport'
        }
      ],
      // 查询参数
      queryParams: {
        investorId: '',
        lpId: '',
        lpIds: '',
        dealId: '',
        dealIndustry: '',
        endDate: undefined,
        reportType: undefined,
        fundId: undefined,
        year: undefined,
        endYear: undefined,
        quarter: undefined,
        endQuarter: undefined,
        pageNum: 1,
        pageSize: 10
      },
      arrayParams: {
        investorIds: [],
        dealIds: [],
        dealIndustrys: []
      },
      // 查询项目参数
      dealParams: {
        investorId: '',
        dealIndustry: ''
      },
      // 所有基金options
      fundOptions: [],
      // 项目options
      dealOptions: [],
      // 项目行业options
      dealIndustryOptions: [],
      quarterArr: [
        {
          label: '一',
          value: '1'
        },
        {
          label: '二',
          value: '2'
        },
        {
          label: '三',
          value: '3'
        },
        {
          label: '四',
          value: '4'
        }
      ],
      filterOptionArr: [],
      lpOptions: []
    }
  },
  created() {
    findFundList({}).then(response => {
      this.fundOptions = response.data
    })
    this.getDicts('deal_industry').then(response => {
      this.dealIndustryOptions = response.data
    })
    const startYear = new Date()
    const startY = 2015
    const endY = startYear.getFullYear() + 20
    for (let i = startY; i < endY; i++) {
      this.filterOptionArr.push(i)
    }
  },
  methods: {
    /**
     * 选择基金回调 获取出资人
     * @author YangMiao 1939724848@qq.com
     * @date   2022/7/21 9:39
     */
    getLpBaseByFundId(fundId) {
      this.queryParams.lpId = undefined
      this.queryParams.lpIds = undefined
      findLpBaseList({ fundId: fundId }).then(response => {
        this.lpOptions = response.rows
      })
    },
    // 生成Quarterly报表
    createQuarterlyReport() {
      if (this.queryParams.reportType === 'fundDisclosureReport' || this.queryParams.reportType === 'lpEquityReport') {
        // 后来新增的两个报告
        if (!this.queryParams.year) {
          this.$message.warning('请选择年份')
          return
        }
        if (!this.queryParams.fundId) {
          this.$message.warning('请选择基金')
          return
        }
        if (!this.queryParams.quarter) {
          this.$message.warning('请选择季度')
          return
        }
        if (this.queryParams.reportType === 'lpEquityReport') {
          if (!this.queryParams.lpIds) {
            this.queryParams.lpId = ''
            this.lpOptions.forEach(lp => {
              this.queryParams.lpId += lp.lpId + ','
            })
            if (this.queryParams.lpId) {
              this.queryParams.lpId = this.queryParams.lpId.substring(0, this.queryParams.lpId.length - 1)
            }
          } else {
            this.queryParams.lpId = this.queryParams.lpIds
          }
          if (!this.queryParams.endYear) {
            this.$message.warning('请选择结束年份')
            return
          }
          if (!this.queryParams.endQuarter) {
            this.$message.warning('请选择结束季度')
            return
          }
        }

        // 正式开始下载
        if (this.queryParams.reportType === 'fundDisclosureReport') {
          axios({
            method: 'post',
            url: process.env.VUE_APP_BASE_API + '/writingReports/exportFundDisclosureReport',
            data: this.queryParams,
            responseType: 'blob',
            headers: { 'Authorization': 'Bearer ' + getToken() }
          }).then(res => {
            const blob = res.data
            const reader = new FileReader()
            reader.readAsDataURL(blob)
            reader.onload = (e) => {
              const a = document.createElement('a')
              // 获取选择的基金名称
              a.download = `基金信披报告.docx`
              a.href = e.target.result
              document.body.appendChild(a)
              a.click()
              document.body.removeChild(a)
              this.loadingFile = false
            }
          })
        } else if (this.queryParams.reportType === 'lpEquityReport') {
          // lp权益报告
          axios({
            method: 'post',
            url: process.env.VUE_APP_BASE_API + '/writingReports/exportLPRightsAndInterestsReport',
            data: this.queryParams,
            responseType: 'blob',
            headers: { 'Authorization': 'Bearer ' + getToken() }
          }).then(res => {
            const blob = res.data
            const reader = new FileReader()
            reader.readAsDataURL(blob)
            reader.onload = (e) => {
              const a = document.createElement('a')
              // 获取选择的基金名称
              const fileName = '【LP权益报告】'
              a.download = fileName + `.zip`
              a.href = e.target.result
              document.body.appendChild(a)
              a.click()
              document.body.removeChild(a)
              this.loadingFile = false
            }
          })
          // axios({
          //   method: 'post',
          //   url: process.env.VUE_APP_BASE_API + '/writingReports/exportLPRightsAndInterestsReport',
          //   data: this.queryParams,
          //   responseType: 'blob',
          //   headers: { 'Authorization': 'Bearer ' + getToken() }
          // }).then(res => {
          //   const blob = res.data
          //   const reader = new FileReader()
          //   reader.readAsDataURL(blob)
          //   reader.onload = (e) => {
          //     const a = document.createElement('a')
          //     a.download = `LP权益报告.docx`
          //     a.href = e.target.result
          //     document.body.appendChild(a)
          //     a.click()
          //     document.body.removeChild(a)
          //     this.loadingFile = false
          //   }
          // })
        }
      } else {
        if (!this.queryParams.endDate) {
          this.msgError('请选择截止日期!')
          return
        }
        if (this.arrayParams.dealIds.length === 0) {
          // 如果项目选择为空，那么默认选中的就是所有的项目
          this.dealOptions.forEach(deal => {
            this.queryParams.dealId += deal.id + ','
          })
        } else {
          // 拼接项目ID查询条件
          this.queryParams.dealId = ''
          this.arrayParams.dealIds.forEach(item => {
            this.queryParams.dealId += item + ','
          })
        }
        if (this.queryParams.dealId) {
          this.queryParams.dealId = this.queryParams.dealId.substring(0, this.queryParams.dealId.length - 1)
        } else {
          this.msgError('查询条件不能为空!')
          return
        }
        // 拼接基金ID查询条件
        if (this.arrayParams.investorIds) {
          this.queryParams.investorId = ''
          this.arrayParams.investorIds.forEach(item => {
            this.queryParams.investorId += '' + item + ','
          })
          if (this.queryParams.investorId) {
            this.queryParams.investorId = this.queryParams.investorId.substring(0, this.queryParams.investorId.length - 1)
          }
        } else {
          this.queryParams.investorId = ''
        }
        this.loadingFile = true
        // 准备下载
        axios({
          method: 'post',
          url: process.env.VUE_APP_BASE_API + '/dashboard/exportQuarterlyReport',
          data: this.queryParams,
          responseType: 'blob',
          headers: { 'Authorization': 'Bearer ' + getToken() }
        }).then(res => {
          const blob = res.data
          const reader = new FileReader()
          reader.readAsDataURL(blob)
          reader.onload = (e) => {
            const a = document.createElement('a')
            // 获取选择的基金名称
            const fileName = '【撰写报告】'
            a.download = fileName + `.zip`
            a.href = e.target.result
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
            this.loadingFile = false
          }
        })
      }
    },
    // 生成报告
    createFile(item) {
      this.queryParams.reportType = item.reportType
      if (this.queryParams.reportType === 'fundDisclosureReport' || this.queryParams.reportType === 'lpEquityReport') {
        this.fileOpenTwo = true
      } else {
        this.fileOpen = true
      }
    },
    // 取消按钮
    formCancel() {
      this.fileOpen = false
      this.fileOpenTwo = false
      Object.assign(this.$data.queryParams, this.$options.data().queryParams)
      this.reset()
    },
    // 格式化项目行业字典
    dealIndustryFormat(row) {
      return this.selectDictLabel(this.dealIndustryOptions, row.dashboardVO.sector1)
    },
    // 根据基金投资主体ID和项目行业，获取项目信息
    changeData() {
      this.dealOptions = []
      this.queryParams.dealId = ''
      this.appendSearch()
      if (this.queryParams.reportType === 'fundValueCreationChinaPortolio' || this.queryParams.reportType === 'quarterlyReviewbydeal') {
        this.dealParams.dealStatus = 'NOTQ'
      }
      if (this.dealParams.investorId || this.dealParams.dealIndustry) {
        listDeal(this.dealParams).then(res => {
          this.dealOptions = res.rows
        })
      }
    },
    // 拼接查询条件
    appendSearch() {
      // 基金ID
      if (this.arrayParams.investorIds) {
        this.queryParams.investorId = ''
        this.dealParams.investorId = ''
        this.arrayParams.investorIds.forEach(item => {
          this.queryParams.investorId += '' + item + ','
        })
        if (this.queryParams.investorId) {
          this.queryParams.investorId = this.queryParams.investorId.substring(0, this.queryParams.investorId.length - 1)
          this.dealParams.investorId = this.queryParams.investorId
        }
      } else {
        this.queryParams.investorId = ''
        this.dealParams.investorId = ''
      }
      // 项目ID
      if (this.arrayParams.dealIds) {
        this.queryParams.dealId = ''
        this.arrayParams.dealIds.forEach(item => {
          this.queryParams.dealId += '' + item + ','
        })
        if (this.queryParams.dealId) {
          this.queryParams.dealId = this.queryParams.dealId.substring(0, this.queryParams.dealId.length - 1)
        }
      }
      // 项目行业
      if (this.arrayParams.dealIndustrys) {
        this.queryParams.dealIndustry = ''
        this.dealParams.dealIndustry = ''
        this.arrayParams.dealIndustrys.forEach(item => {
          this.queryParams.dealIndustry += '' + item + ','
        })
        if (this.queryParams.dealIndustry) {
          this.queryParams.dealIndustry = this.queryParams.dealIndustry.substring(0, this.queryParams.dealIndustry.length - 1)
          this.dealParams.dealIndustry = this.queryParams.dealIndustry
        }
      } else {
        this.queryParams.dealIndustry = ''
        this.dealParams.dealIndustry = ''
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.arrayParams.dealIds = []
      this.arrayParams.investorIds = []
      this.arrayParams.dealIndustrys = []
      this.queryParams.endDate = ''
      this.queryParams.dealIndustry = ''
      this.queryParams.investorId = ''
      this.queryParams.dealId = ''
      this.dealOptions = []
      this.queryHandle()
    }
  }
}
</script>
